"""
IoT数据处理管理器

统一管理所有IoT设备数据处理器，提供统一的处理接口
"""

import asyncio
from typing import Dict, Any, Optional, Callable

from ..handlers import (
    LocationHandler, HealthHandler, BatteryHandler, 
    WarningHandler, AudioHandler
)


class IoTHandlerManager:
    """IoT数据处理管理器"""
    
    def __init__(self):
        """初始化处理器管理器"""
        # 初始化所有处理器
        self._handlers = {
            'location': LocationHandler(),
            'health': HealthHandler(),
            'battery': BatteryHandler(),
            'warning': WarningHandler(),
            'audio': AudioHandler()
        }
        
        # 数据类型映射（兼容原有的HANDLER_MAPPER）
        self._type_mapping = {
            'location': 'location',
            'health': 'health',
            'battery': 'battery',      # 原来的handle_step
            'warning': 'warning',
            'audio': 'audio'
        }
    
    async def process_data(self, data_type: str, device_id: str, 
                          data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        """
        处理IoT设备数据
        
        Args:
            data_type: 数据类型 ('location', 'health', 'battery', 'warning', 'audio')
            device_id: 设备ID
            data: 设备数据
            
        Returns:
            处理结果，失败时返回None
        """
        # 获取对应的处理器
        handler = self._get_handler(data_type)
        if not handler:
            return {"error": f"未知的数据类型: {data_type}"}
        
        # 使用基类的错误处理包装器
        return await handler.process_with_error_handling(device_id, data, data_type)
    
    async def process_multiple_data(self, data_list: list) -> list:
        """
        批量处理多个设备数据
        
        Args:
            data_list: 数据列表，每个元素包含 {data_type, device_id, data}
            
        Returns:
            处理结果列表
        """
        tasks = []
        for item in data_list:
            task = self.process_data(
                item.get('data_type'),
                item.get('device_id'),
                item.get('data')
            )
            tasks.append(task)
        
        return await asyncio.gather(*tasks, return_exceptions=True)
    
    def _get_handler(self, data_type: str):
        """
        获取指定类型的数据处理器
        
        Args:
            data_type: 数据类型
            
        Returns:
            处理器实例，未找到时返回None
        """
        mapped_type = self._type_mapping.get(data_type)
        return self._handlers.get(mapped_type)
    
    def get_handler_status(self) -> Dict[str, bool]:
        """
        获取所有处理器的状态
        
        Returns:
            处理器状态字典
        """
        return {
            data_type: handler is not None
            for data_type, handler in self._handlers.items()
        }
    
    async def health_check(self) -> Dict[str, Any]:
        """
        执行健康检查
        
        Returns:
            健康检查结果
        """
        results = {
            'status': 'healthy',
            'handlers': {},
            'total_handlers': len(self._handlers),
            'active_handlers': 0
        }
        
        for data_type, handler in self._handlers.items():
            try:
                # 简单检查处理器是否可用
                handler_status = {
                    'available': handler is not None,
                    'class_name': handler.__class__.__name__ if handler else None
                }
                results['handlers'][data_type] = handler_status
                
                if handler_status['available']:
                    results['active_handlers'] += 1
                    
            except Exception as e:
                results['handlers'][data_type] = {
                    'available': False,
                    'error': str(e)
                }
        
        # 判断整体健康状态
        if results['active_handlers'] < results['total_handlers']:
            results['status'] = 'degraded'
        if results['active_handlers'] == 0:
            results['status'] = 'unhealthy'
        
        return results
    
    # 兼容性方法：提供原有HANDLER_MAPPER的调用方式
    async def location_handle_new(self, location_data) -> Optional[Any]:
        """兼容原有的location_handle_new函数"""
        return await self._handlers['location'].handle(
            location_data.device_id, location_data.model_dump()
        )
    
    async def handle_health(self, health_data) -> Optional[Any]:
        """兼容原有的handle_health函数"""
        return await self._handlers['health'].handle(
            health_data.device_id, health_data.model_dump()
        )
    
    async def handle_step(self, battery_data) -> Optional[Any]:
        """兼容原有的handle_step函数"""
        return await self._handlers['battery'].handle(
            battery_data.device_id, battery_data.model_dump()
        )
    
    async def handle_warning(self, warning_data) -> Optional[Any]:
        """兼容原有的handle_warning函数"""
        return await self._handlers['warning'].handle(
            warning_data.device_id, warning_data.model_dump()
        )
    
    async def handle_audio(self, audio_data) -> Optional[Any]:
        """兼容原有的handle_audio函数"""
        return await self._handlers['audio'].handle(
            audio_data.device_id, audio_data.model_dump()
        )


# 全局单例实例
_iot_manager = None

def get_iot_handler_manager() -> IoTHandlerManager:
    """
    获取IoT处理器管理器单例
    
    Returns:
        IoTHandlerManager实例
    """
    global _iot_manager
    if _iot_manager is None:
        _iot_manager = IoTHandlerManager()
    return _iot_manager


# 兼容性函数：保持与原有代码的兼容性
async def location_handle_new(location_data):
    """兼容原有的location_handle_new函数调用"""
    manager = get_iot_handler_manager()
    return await manager.location_handle_new(location_data)

async def handle_health(health_data):
    """兼容原有的handle_health函数调用"""
    manager = get_iot_handler_manager()
    return await manager.handle_health(health_data)

async def handle_step(battery_data):
    """兼容原有的handle_step函数调用"""
    manager = get_iot_handler_manager()
    return await manager.handle_step(battery_data)

async def handle_warning(warning_data):
    """兼容原有的handle_warning函数调用"""
    manager = get_iot_handler_manager()
    return await manager.handle_warning(warning_data)

async def handle_audio(audio_data):
    """兼容原有的handle_audio函数调用"""
    manager = get_iot_handler_manager()
    return await manager.handle_audio(audio_data)